package com.aiit.controller.user;


import com.aiit.constant.JwtClaimsConstant;
import com.aiit.dto.TeaOrderDTO;
import com.aiit.dto.UserAdressDTO;
import com.aiit.dto.UserLoginDTO;
import com.aiit.entity.TeaOrder;
import com.aiit.entity.User;
import com.aiit.entity.UserAddress;
import com.aiit.properties.JwtProperties;
import com.aiit.result.Result;
import com.aiit.service.UserService;
import com.aiit.utils.JwtUtil;
import com.aiit.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员管理
 */
@RestController
@RequestMapping("/user/shop")
@Slf4j
@Api(tags = "会员相关接口")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/register")
    @ApiOperation("新增会员")
    public Result save(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("新增会员：{}", userLoginDTO);
        System.out.println("当前线程的id:" + Thread.currentThread().getId());
        userService.save(userLoginDTO);
        return Result.success();
    }


    /**
     * 登录
     *
     * @param
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("会员登录")
    public Result<EmployeeLoginVO> login(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request) {
        log.info("会员登录：{}", userLoginDTO);
        String storedVerificationCode = (String) request.getSession().getAttribute("verificationCode");
        try {
            log.info("获取的 session: {}：", request.getSession());
            log.info("storedVerificationCode:", storedVerificationCode);

            if (storedVerificationCode == null) {
                log.warn("获取的 session: {}", request.getSession());
                return Result.error("验证码已过期或无效，请重新获取验证码。");
            }
            User user = userService.login(userLoginDTO, storedVerificationCode);

            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.EMP_ID, user.getId());
            String token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims);
            log.info(jwtProperties.getAdminSecretKey());
            EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                    .id(user.getId())
                    .userName(user.getUsername())

                    .token(token)
                    .build();

            return Result.success(employeeLoginVO);
        } catch (Exception e) {
            log.error("会员登录失败：", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    @GetMapping("/page")
    @ApiOperation("会员信息查询")
    public Result<User> page(@RequestParam(required = false) String username) {
        UserLoginDTO userLoginDTO = new UserLoginDTO();
        userLoginDTO.setUsername(username);
        log.info("会员信息查询,参数为：{}", userLoginDTO);
        User pageResult = userService.pageQuery(userLoginDTO);
        return Result.success(pageResult);
    }

    @GetMapping("/address")
    @ApiOperation("会员地址查询")
    public Result<UserAddress> address(@RequestParam(required = false) String username) {
        UserAdressDTO userAdressDTO = new UserAdressDTO();
        userAdressDTO.setUsername(username);
        log.info("会员地址查询,参数为：{}", userAdressDTO);
        UserAddress addressResult = userService.address(userAdressDTO);
        return Result.success(addressResult);
    }

    @PutMapping("/address/update")
    @ApiOperation("修改地址信息")
    public Result Update(@RequestParam(required = false) String username, String address) {
        UserAdressDTO userAdressDTO = new UserAdressDTO();
        userAdressDTO.setUsername(username);
        userAdressDTO.setAddress(address);
        log.info("修改地址信息：{}", username, address);
        userService.update(userAdressDTO);

        return Result.success();
    }

    @GetMapping("/orders")
    @ApiOperation("会员订单查询")
    public Result<List<TeaOrder>> orders(@RequestParam(required = false) String username) {
        TeaOrderDTO teaOrderDTO = new TeaOrderDTO();
        teaOrderDTO.setUsername(username);
        log.info("会员订单查询,参数为：{}", teaOrderDTO);
        List<TeaOrder> orderResult = userService.order(teaOrderDTO);
        return Result.success(orderResult);
    }

    @PutMapping("/payment/update")
    @ApiOperation("下单成功后的请求")
    public Result UpdatePayment2(@RequestParam(required = false) String username, @RequestParam(required = false) Long id) {
        TeaOrderDTO teaOrderDTO = new TeaOrderDTO();
        teaOrderDTO.setUsername(username);
        teaOrderDTO.setId(id);
        log.info("修改订单状态信息信息：{}", username, id);
        userService.updatePayment(teaOrderDTO);

        return Result.success();
    }

    @GetMapping("/order/detail")
    @ApiOperation("会员订单查询")
    public Result<TeaOrder> ordersDetail(@RequestParam(required = false) Long id) {
        TeaOrderDTO teaOrderDTO = new TeaOrderDTO();
        teaOrderDTO.setId(id);
        log.info("会员订单查询,参数为：{}", teaOrderDTO);
        TeaOrder orderDetailResult = userService.orderDetail(teaOrderDTO);
        return Result.success(orderDetailResult);
    }


}




